﻿using Aspose.Cells;
using DevExpress.XtraLayout.Utils;
using DevExpress.XtraTreeList.Nodes;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
using System.Windows.Forms;
using XuanFe.AppLaunch.Common;
using XuanFe.Database.BLL;
using XuanFe.Database.DAL;
using XuanFe.Database.Model;

namespace XuanFe.AppLaunch
{
    public partial class CityForm : DevExpress.XtraEditors.XtraForm
    {
        private const string m_ModuleId = "0105";

        private int colIndexCITY_ID = 0;
        private int colIndexCITY_NAME = 0;
        private int colIndexNATION_ID = 0;
        private int colIndexNATION_NAME = 0;
        private int colIndexSORT_INDEX = 0;
        private int colIndexAIRPORT_NAME = 0;
        private int colIndexAIRPORT_CODE_3 = 0;
        private int colIndexAIRPORT_CODE_4 = 0;
        private int colIndexCHINESE_SPELL = 0;
        private int colIndexENGLISH_NAME = 0;

        private ManageState m_ManageState;
        private List<NationModel> m_Nations = new List<NationModel>();

        public CityForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 设置界面状态
        /// </summary>
        /// <param name="state"></param>
        private void SetManageState(ManageState state)
        {
            this.m_ManageState = state;

            this.errorProvider1.ClearErrors();

            switch (state)
            {
                case ManageState.None:
                    this.gridControl1.Enabled = true;

                    this.btnAppend.Enabled = true;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.txtChineseSpell.Text = string.Empty;
                    this.seSortIndex.Value = 0;
                    this.txtAirportName.Text = string.Empty;
                    this.txtEnglish.Text = string.Empty;
                    this.txtCode3.Text = string.Empty;
                    this.txtCode4.Text = string.Empty;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.txtChineseSpell.Enabled = false;
                    this.seSortIndex.Enabled = false;
                    this.txtAirportName.Enabled = false;
                    this.txtEnglish.Enabled = false;
                    this.txtCode3.Enabled = false;
                    this.txtCode4.Enabled = false;
                    this.cmbNation.Enabled = false;
                    break;
                case ManageState.Append:
                case ManageState.AppendChild:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "取消(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.txtChineseSpell.Text = string.Empty;
                    this.seSortIndex.Value = 0;
                    this.txtAirportName.Text = string.Empty;
                    this.txtEnglish.Text = string.Empty;
                    this.txtCode3.Text = string.Empty;
                    this.txtCode4.Text = string.Empty;

                    this.txtId.Enabled = true;
                    this.txtName.Enabled = true;
                    this.txtChineseSpell.Enabled = true;
                    this.seSortIndex.Enabled = true;
                    this.txtAirportName.Enabled = true;
                    this.txtEnglish.Enabled = true;
                    this.txtCode3.Enabled = true;
                    this.txtCode4.Enabled = true;
                    this.cmbNation.Enabled = true;

                    this.txtId.Focus();
                    break;
                case ManageState.Modify:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "取消(&C)";

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = true;
                    this.txtChineseSpell.Enabled = true;
                    this.seSortIndex.Enabled = true;
                    this.txtAirportName.Enabled = true;
                    this.txtEnglish.Enabled = true;
                    this.txtCode3.Enabled = true;
                    this.txtCode4.Enabled = true;
                    this.cmbNation.Enabled = true;

                    this.txtName.Focus();
                    break;
                case ManageState.Delete:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.txtChineseSpell.Enabled = false;
                    this.seSortIndex.Enabled = false;
                    this.txtAirportName.Enabled = false;
                    this.txtEnglish.Enabled = false;
                    this.txtCode3.Enabled = false;
                    this.txtCode4.Enabled = false;
                    this.cmbNation.Enabled = false;
                    break;
                case ManageState.Save:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.txtChineseSpell.Enabled = false;
                    this.seSortIndex.Enabled = false;
                    this.txtAirportName.Enabled = false;
                    this.txtEnglish.Enabled = false;
                    this.txtCode3.Enabled = false;
                    this.txtCode4.Enabled = false;
                    this.cmbNation.Enabled = false;
                    break;
                case ManageState.Browse:
                case ManageState.Cancel:
                    this.gridControl1.Enabled = true;

                    this.btnAppend.Enabled = true;
                    this.btnModify.Enabled = this.IsModify();
                    this.btnDelete.Enabled = this.IsDelete();
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = true;
                    this.btnCancel.Text = "关闭(&C)";

                    this.txtId.Text = string.Empty;
                    this.txtName.Text = string.Empty;
                    this.txtChineseSpell.Text = string.Empty;
                    this.seSortIndex.Value = 0;
                    this.txtAirportName.Text = string.Empty;
                    this.txtEnglish.Text = string.Empty;
                    this.txtCode3.Text = string.Empty;
                    this.txtCode4.Text = string.Empty;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.txtChineseSpell.Enabled = false;
                    this.seSortIndex.Enabled = false;
                    this.txtAirportName.Enabled = false;
                    this.txtEnglish.Enabled = false;
                    this.txtCode3.Enabled = false;
                    this.txtCode4.Enabled = false;
                    this.cmbNation.Enabled = false;

                    this.gridView1_SelectionChanged(null, null);
                    break;
                default:
                    this.gridControl1.Enabled = false;

                    this.btnAppend.Enabled = false;
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;

                    this.txtId.Enabled = false;
                    this.txtName.Enabled = false;
                    this.txtChineseSpell.Enabled = false;
                    this.seSortIndex.Enabled = false;
                    this.txtAirportName.Enabled = false;
                    this.txtEnglish.Enabled = false;
                    this.txtCode3.Enabled = false;
                    this.txtCode4.Enabled = false;
                    this.cmbNation.Enabled = false;
                    break;
            }
        }

        private bool IsModify()
        {
            return (this.gridView1.RowCount > 0 && this.gridView1.FocusedRowHandle >= 0);
        }

        private bool IsDelete()
        {
            return (this.gridView1.RowCount > 0 && this.gridView1.FocusedRowHandle >= 0);
        }

        /// <summary>
        /// 清空记录
        /// </summary>
        private void ClearRecordToGrid()
        {
            this.gridView1.BeginUpdate();
            this.gridView1.Columns.Clear();

            DevExpress.XtraGrid.Columns.GridColumn c;
            int visibleIndex = 0;

            this.colIndexCITY_ID = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "CITY_ID";
            c.Caption = "编码";
            c.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            c.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] {
            new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Custom, "CITY_ID", "总数")});
            this.gridView1.Columns.Add(c);

            this.colIndexCITY_NAME = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "CITY_NAME";
            c.Caption = "城市名称";
            c.Fixed = DevExpress.XtraGrid.Columns.FixedStyle.Left;
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            c.Summary.AddRange(new DevExpress.XtraGrid.GridSummaryItem[] {
            new DevExpress.XtraGrid.GridColumnSummaryItem(DevExpress.Data.SummaryItemType.Count)});
            this.gridView1.Columns.Add(c);

            this.colIndexNATION_ID = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "NATION_ID";
            c.Caption = "国家编码";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = false;
            this.gridView1.Columns.Add(c);

            this.colIndexNATION_NAME = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "NATION_NAME";
            c.Caption = "所属国家";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexCHINESE_SPELL = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "CHINESE_SPELL";
            c.Caption = "全拼";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexSORT_INDEX = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "SORT_INDEX";
            c.Caption = "排序号";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexAIRPORT_NAME = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "AIRPORT_NAME";
            c.Caption = "机场名称";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexAIRPORT_CODE_3 = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "AIRPORT_CODE_3";
            c.Caption = "机场3字码";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexAIRPORT_CODE_4 = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "AIRPORT_CODE_4";
            c.Caption = "机场4字码";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.colIndexENGLISH_NAME = this.gridView1.Columns.Count;
            c = new DevExpress.XtraGrid.Columns.GridColumn();
            c.FieldName = "ENGLISH_NAME";
            c.Caption = "英文";
            c.OptionsColumn.ReadOnly = true;
            c.OptionsColumn.AllowFocus = false;
            c.Visible = true;
            c.VisibleIndex = visibleIndex++;
            this.gridView1.Columns.Add(c);

            this.gridView1.EndUpdate();
        }

        /// <summary>
        /// 加载记录
        /// </summary>
        private void LoadRecordToGrid()
        {
            using (DataSet ds = CityDAL.Instance.GetDataSet())
            {
                this.gridControl1.DataSource = ds.Tables[0];
                this.gridView1.BestFitColumns();

                if (this.gridView1.RowCount > 0)
                {
                    this.SetManageState(ManageState.Browse);
                }
                else
                {
                    this.SetManageState(ManageState.None);
                }
            }
        }
        private void BuildAll()
        {
            this.m_Nations = NationDAL.Instance.Gets();

            this.cmbNation.Properties.Items.Clear();
            this.cmbNation.Properties.Items.AddRange(this.m_Nations);
        }

        /// <summary>
        /// 添加记录
        /// </summary>
        /// <returns></returns>
        private bool AppendRecord()
        {
            try
            {
                CityModel model = new CityModel()
                {
                    Id = this.txtId.Text.Trim(),
                    Name = this.txtName.Text.Trim(),
                    ChineseSpell = this.txtChineseSpell.Text.Trim(),
                    SortIndex = Convert.ToInt32(this.seSortIndex.Value),
                    AirportName = this.txtAirportName.Text.Trim(),
                    EnglishName = this.txtEnglish.Text.Trim(),
                    AirportCode3 = this.txtCode3.Text.Trim(),
                    AirportCode4 = this.txtCode4.Text.Trim(),
                    NationId = ((NationModel)this.cmbNation.SelectedItem).Id,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            CityDAL.Instance.Insert(tran, model);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 修改记录
        /// </summary>
        /// <returns></returns>
        private bool ModifyRecord()
        {
            try
            {
                CityModel model = new CityModel()
                {
                    Id = this.txtId.Text.Trim(),
                    Name = this.txtName.Text.Trim(),
                    ChineseSpell = this.txtChineseSpell.Text.Trim(),
                    SortIndex = Convert.ToInt32(this.seSortIndex.Value),
                    AirportName = this.txtAirportName.Text.Trim(),
                    EnglishName = this.txtEnglish.Text.Trim(),
                    AirportCode3 = this.txtCode3.Text.Trim(),
                    AirportCode4 = this.txtCode4.Text.Trim(),
                    NationId = ((NationModel)this.cmbNation.SelectedItem).Id,
                    LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                    LastModifiedDate = DateTime.Now,
                };

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            CityDAL.Instance.Update(tran, model);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }
        private bool ImportRecord(string fileName)
        {
            try
            {
                Workbook workbook = new Workbook(fileName);
                Worksheet worksheet = workbook.Worksheets["机场列表"];
                Cells cells = worksheet.Cells;

                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            string currentCountryCode = string.Empty;
                            int currentCountrySortIndex = 0;
                            int currentCitySortIndex = 0;
                            System.Globalization.TextInfo textInfo = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo;

                            for (int i = 1; i < cells.MaxDataRow + 1; i++)
                            {
                                string countryCode = cells[i, 0].StringValue.Trim().ToUpper();
                                string country = cells[i, 1].StringValue.Trim();
                                string ctiy = cells[i, 2].StringValue.Trim();
                                string code3 = cells[i, 3].StringValue.Trim().ToUpper();
                                string code4 = cells[i, 4].StringValue.Trim().ToUpper();
                                string airport = cells[i, 5].StringValue.Trim();
                                string airport_en = textInfo.ToTitleCase(cells[i, 6].StringValue.Trim().ToLower());

                                if (!string.Equals(countryCode, currentCountryCode))
                                {
                                    // 不等于上一记录
                                    currentCountryCode = countryCode;
                                    currentCitySortIndex = 0;
                                    if (!NationDAL.Instance.Exist(tran, currentCountryCode))
                                    {
                                        NationModel countryModel = new NationModel()
                                        {
                                            Id = currentCountryCode,
                                            Name = country,
                                            SortIndex = currentCountrySortIndex++,
                                            LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                                            LastModifiedDate = DateTime.Now,
                                        };
                                        NationDAL.Instance.Insert(tran, countryModel);
                                    }
                                }

                                if (!CityDAL.Instance.Exist(tran, code3))
                                {
                                    CityModel model = new CityModel()
                                    {
                                        Id = code3,
                                        Name = ctiy,
                                        ChineseSpell = MyPinYin.PinYinConverter.Get(ctiy),
                                        SortIndex = currentCitySortIndex++,
                                        AirportName = airport,
                                        EnglishName = airport_en,
                                        AirportCode3 = code3,
                                        AirportCode4 = code4,
                                        NationId = currentCountryCode,
                                        LastModifiedStaffId = LoginInfo.Instance.StaffLogon.Staff.Id,
                                        LastModifiedDate = DateTime.Now,
                                    };
                                    CityDAL.Instance.Insert(tran, model);
                                }
                            }

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool DeleteRecord(string Code)
        {
            try
            {
                using (DbConnection conn = MySQLHelper.Instance.CreateConnection())
                {
                    try
                    {
                        if (conn.State != ConnectionState.Open)
                            conn.Open();

                        DbTransaction tran = conn.BeginTransaction();
                        try
                        {
                            CityDAL.Instance.Delete(tran, Code);

                            tran.Commit();
                            return (true);
                        }
                        catch
                        {
                            tran.Rollback();
                            return (false);
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
            catch
            {
                return (false);
            }
        }

        /// <summary>
        /// 记录是否正在使用
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool RecordIsUsing(string Code)
        {
            if (!BookingFlightDAL.Instance.DepartureCityUsing(Code))
                return false;
            if (!BookingFlightDAL.Instance.ArrivalCityUsing(Code))
                return false;
            if (!BookingTicketDAL.Instance.DepartureCityUsing(Code))
                return false;
            if (!BookingTicketDAL.Instance.ArrivalCityUsing(Code))
                return false;
            return true;
        }

        /// <summary>
        /// 记录是否已存在
        /// </summary>
        /// <param name="UrlCd"></param>
        /// <returns></returns>
        private bool RecordIsExist(string Code)
        {
            if (CityDAL.Instance.Exist(Code))
                return (true);

            return (false);
        }
        /// <summary>
        /// 获取最大的编码
        /// </summary>
        /// <param name="dataTable">数据源</param>
        /// <param name="columnName">数据源列名</param>
        /// <returns></returns>
        private string GetMaxId(DataTable dataTable, string columnName)
        {
            string result = "0001";
            if (dataTable == null) return result;
            int count = dataTable.Rows.Count;

            // 获取最大的长度
            int maxlen = 0;
            for (int i = 0; i < count; i++)
            {
                string v = dataTable.Rows[i][columnName].ToString();
                if (v.Length > maxlen)
                    maxlen = v.Length;
            }

            // 获取最大长度的记录，并排序
            DataRow[] rows = dataTable.Select(string.Format("len({0})={1}", columnName, maxlen), string.Format("{0} desc", columnName));
            count = rows.Length;
            if (count == 0) return result;

            // 获取第一条记录
            string maxid = rows[0][columnName].ToString();
            if (Global.Instance.IsInt(maxid))
            {
                // 整型，直接累计并返回
                result = Convert.ToString(Convert.ToDecimal(maxid) + 1).PadLeft(maxid.Length, '0');
            }
            else
            {
                // 非整型，截取最右边为数字那部分
                string code = string.Empty;
                for (int i = maxid.Length - 1; i >= 0; i--)
                {
                    char c = maxid[i];
                    if (Char.IsNumber(c))
                    {
                        code = string.Concat(c.ToString(), code);
                        continue;
                    }
                    break;
                }
                if (!string.IsNullOrEmpty(code))
                {
                    // 成功截取最右边数字部分
                    result = string.Concat(maxid.Substring(0, maxid.Length - code.Length), Convert.ToString(Convert.ToDecimal(code) + 1).PadLeft(code.Length, '0'));
                }
                else
                {
                    // 截取失败
                    result = string.Concat(maxid, "1");
                }
            }
            return result;
        }
        /// <summary>
        /// 描述是否已经存在
        /// </summary>
        /// <param name="Code"></param>
        /// <param name="Desc"></param>
        /// <returns></returns>
        private bool DescriptionIsExist(string Code, string Desc)
        {
            if (StaffDAL.Instance.Exist(Code, Desc))
                return (true);

            return (false);
        }
        /// <summary>
        /// 有效性校验
        /// </summary>
        /// <returns></returns>
        private bool ValidityCheck()
        {
            this.errorProvider1.ClearErrors();
            string message = string.Empty;
            if (Global.Instance.MandatoryFieldEmpty(this.txtId, false, ref message))
            {
                this.errorProvider1.SetError(this.txtId, message);
                this.txtId.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtName, message);
                this.txtName.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.cmbNation, false, ref message))
            {
                this.errorProvider1.SetError(this.cmbNation, message);
                this.cmbNation.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtAirportName, false, ref message))
            {
                this.errorProvider1.SetError(this.txtAirportName, message);
                this.txtAirportName.Focus();
                return (false);
            }
            if (Global.Instance.MandatoryFieldEmpty(this.txtCode3, false, ref message))
            {
                this.errorProvider1.SetError(this.txtCode3, message);
                this.txtCode3.Focus();
                return (false);
            }
            if (this.DescriptionIsExist(this.txtId.Text.Trim(), this.txtName.Text.Trim()))
            {
                this.errorProvider1.SetError(this.txtName, "该记录已存在！");
                this.txtName.Focus();
                return (false);
            }
            return (true);
        }

        private bool CheckSelected()
        {
            return (this.gridView1.SelectedRowsCount > 0);
        }

        private void CityForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.SetManageState(ManageState.None);

                this.ClearRecordToGrid();

                this.BuildAll();

                this.LoadRecordToGrid();

                StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, "浏览记录");

                // 新增城市信息
                if (!LoginInfo.Instance.CheckPermission("010502"))
                {
                    this.lcAppend.Visibility = LayoutVisibility.Never;
                }
                // 修改城市信息
                if (!LoginInfo.Instance.CheckPermission("010503"))
                {
                    this.lcModify.Visibility = LayoutVisibility.Never;
                }
                // 删除城市信息
                if (!LoginInfo.Instance.CheckPermission("010504"))
                {
                    this.lcDelete.Visibility = LayoutVisibility.Never;
                }
                // 导入城市信息
                if (!LoginInfo.Instance.CheckPermission("010505"))
                {
                    this.lcImport.Visibility = LayoutVisibility.Never;
                }
                if (this.lcAppend.Visibility == LayoutVisibility.Never
                    && this.lcModify.Visibility == LayoutVisibility.Never)
                {
                    this.lcSave.Visibility = LayoutVisibility.Never;
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                if (this.gridView1.SelectedRowsCount != 1) return;

                int r = this.gridView1.GetSelectedRows()[0];
                if (r < 0)
                {
                    this.btnModify.Enabled = false;
                    this.btnDelete.Enabled = false;
                    return;
                }
                this.btnModify.Enabled = true;
                this.btnDelete.Enabled = true;

                this.txtId.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexCITY_ID]));
                this.txtName.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexCITY_NAME]));
                this.txtChineseSpell.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexCHINESE_SPELL]));
                this.cmbNation.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexNATION_NAME]));
                this.seSortIndex.Value = Convert.ToDecimal(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexSORT_INDEX]));
                this.txtAirportName.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexAIRPORT_NAME]));
                this.txtCode3.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexAIRPORT_CODE_3]));
                this.txtCode4.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexAIRPORT_CODE_4]));
                this.txtEnglish.Text = Convert.ToString(this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexENGLISH_NAME]));
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnAppend_Click(object sender, EventArgs e)
        {
            try
            {
                this.SetManageState(ManageState.Append);
                this.txtId.Text = this.GetMaxId(this.gridControl1.DataSource as DataTable, this.gridView1.Columns[this.colIndexCITY_ID].FieldName);
                this.txtId.SelectAll();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.CheckSelected())
                {
                    Global.Instance.InfoDlg("没有可选的记录！");
                    return;
                }
                this.SetManageState(ManageState.Modify);
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.CheckSelected())
                {
                    Global.Instance.InfoDlg("没有可选的记录！");
                    return;
                }

                if (!Global.Instance.QueryDlg("是否真的要删除所选的记录？")) return;

                Global.Instance.BeginWait();
                this.progressBar1.EditValue = 0;
                this.lciProgressBar.ContentVisible = true;

                int UsingCount = 0, FailedCount = 0;
                double step = 100.00 / this.gridView1.SelectedRowsCount;
                double total = 0;
                foreach (int r in this.gridView1.GetSelectedRows())
                {
                    total += step;
                    this.progressBar1.EditValue = Convert.ToInt32(Math.Round(total));
                    Application.DoEvents();

                    if (r < 0) continue;
                    string id = this.gridView1.GetRowCellValue(r, this.gridView1.Columns[this.colIndexCITY_ID]).ToString();
                    if (!this.RecordIsUsing(id))
                    {
                        if (!this.DeleteRecord(id))
                        {
                            FailedCount++;
                            continue;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("删除编码为“{0}”的记录", id));
                    }
                    else
                    {
                        UsingCount++;
                    }
                }

                if (UsingCount > 0 || FailedCount > 0)
                    Global.Instance.WarningDlg(string.Format("删除完毕！其中有{0}条记录正在使用，{1}条记录删除失败.", UsingCount, FailedCount));

                this.LoadRecordToGrid();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                this.progressBar1.EditValue = 100;
                this.lciProgressBar.ContentVisible = false;
                Global.Instance.EndWait();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.ValidityCheck()) return;

                Global.Instance.BeginWait();
                ManageState state = this.m_ManageState;

                string id = this.txtId.Text.Trim();
                switch (state)
                {
                    case ManageState.Append:
                    case ManageState.AppendChild:
                        if (this.RecordIsExist(id))
                        {
                            this.errorProvider1.SetError(this.txtId, "该记录已存在！");
                            this.txtId.Focus();
                            return;
                        }

                        if (!this.AppendRecord())
                        {
                            Global.Instance.ErrorDlg("保存失败！");
                            return;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("新增编码为“{0}”的记录", id));
                        break;
                    case ManageState.Modify:
                        if (!this.ModifyRecord())
                        {
                            Global.Instance.ErrorDlg("保存失败！");
                            return;
                        }
                        StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, string.Format("修改编码为“{0}”的记录", id));
                        break;
                }

                this.LoadRecordToGrid();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
            finally
            {
                Global.Instance.EndWait();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.m_ManageState == ManageState.Append || this.m_ManageState == ManageState.Append || this.m_ManageState == ManageState.Modify)
                {
                    this.SetManageState(ManageState.Cancel);
                    this.errorProvider1.ClearErrors();
                }
                else
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void gridView1_RowCountChanged(object sender, EventArgs e)
        {
            try
            {
                this.gridView1.SelectRow(this.gridView1.FocusedRowHandle);
                this.btnModify.Enabled = this.IsModify();
                this.btnDelete.Enabled = this.IsDelete();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnAppendChlid_Click(object sender, EventArgs e)
        {
            try
            {
                this.SetManageState(ManageState.AppendChild);
                this.txtId.Text = this.GetMaxId(this.gridControl1.DataSource as DataTable, this.gridView1.Columns[this.colIndexCITY_ID].FieldName);
                this.txtId.SelectAll();
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = string.Empty;
                if (Global.Instance.OpenDialog(ref fileName, "导入机场列表", "XLSX files (*.xlsx)|*.xlsx", ".xlsx"))
                {
                    try
                    {
                        Global.Instance.BeginWait();
                        bool r = this.ImportRecord(fileName);
                        if (r)
                        {
                            Task.Factory.StartNew(() => { this.Invoke(new Action(() => { this.LoadRecordToGrid(); })); });
                            StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, "导入数据成功");
                            Global.Instance.InfoDlg("导入数据成功");
                        }
                        else
                        {
                            StaffLogBLL.Instance.InsertLog(LoginInfo.Instance.StaffLogon.Staff.Id, m_ModuleId, "导入数据失败");
                            Global.Instance.ErrorDlg("导入数据失败");
                        }
                    }
                    finally
                    {
                        Global.Instance.EndWait();
                    }
                }
            }
            catch (Exception ex)
            {
                Global.Instance.ShowExceptionDlg(ex);
            }
        }
    }
}
